package com.service.db;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.service.bean.company.Company;
import com.service.other.Logger;

public class DbConnectionManager {
	
	private static Map<String,ConnectionPool> connectionPools;
	private static DbConnectionManager inst;

	public void close(Company company) {
		try {
			connectionPools.get(company.companyName).closeConnectionPool();
		} catch (SQLException e) {
			e.printStackTrace();
			Logger.err(e);
		}
	}
	
	public void close() {
		try {
			connectionPools.get("main").closeConnectionPool();
		} catch (SQLException e) {
			e.printStackTrace();
			Logger.err(e);
		}
	}

	public DbConnectionManager() {
		if (inst != null){
			return;
		}
		try {
			connectionPools = new HashMap<String,ConnectionPool>();
			inst = this;
		} catch (Exception e) {
			e.printStackTrace();
			Logger.err(e);
		}
	}

	public static PooledConnection getConnection(Company company) {
		PooledConnection conn = null;
		if (inst == null) {
			new DbConnectionManager();
		}
		try {
			if(!connectionPools.containsKey(company.companyName)){
				ConnectionPool connectionPool = new ConnectionPool(company);
				connectionPools.put(company.companyName, connectionPool);
			}
			conn = connectionPools.get(company.companyName).getConnection();
		} catch (Exception e) {
			e.printStackTrace();
			Logger.err(e);
		}
		return conn;
	}
	
	public static PooledConnection getConnection() {
		PooledConnection conn = null;
		if (inst == null) {
			new DbConnectionManager();
		}
		try {
			if(!connectionPools.containsKey("main")){
				ConnectionPool connectionPool = new ConnectionPool();
				connectionPools.put("main", connectionPool);
			}
			conn = connectionPools.get("main").getConnection();
		} catch (Exception e) {
			e.printStackTrace();
			Logger.err(e);
		}
		return conn;
	}
}